package com.anysoft.web;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.bean.BaseBean;
import com.anysoft.bean.QuerySupportRealTimeCancelInfo;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.me.base.BaseWebViewActivity;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.dialog.IcbcDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * 交易详情
 * Created by wyb on 2017/3/26.
 */

public class TransactionDetailActivity extends BaseWebViewActivity {

    private String token = "";

    /**
     * 原交易申请单号、交易帐号、是否可撤单0：不可以 1：可以
     */
    private String url, tradeRequestId, tradeAccountNo, canwithdraw;
    private String canceledBusinessType;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isShowTitleBar(true);
        title.setText("交易详情");
        rightButton.setText("撤单");
        rightButton.setVisibility(View.GONE);
        token = getToken();
        if (getIntent().hasExtra("url")) {
            url = getIntent().getStringExtra("url");
        }
        if (StringUtils.isNullOrEmpty(url)) {
            finish();
        }
        tradeRequestId = "";
        tradeAccountNo = "";
        canwithdraw = "0";
        loadUrl = url;
        HashMap<String, String> hm = handleUrlParams(url);
        if (hm != null) {
            tradeRequestId = hm.get("tradeRequestId");
            tradeAccountNo = hm.get("tradeAccountNo");
            canwithdraw = hm.get("canwithdraw");
            canceledBusinessType = hm.get("businesstype");
        }
        if ("1".equals(canwithdraw)) {
            rightButton.setVisibility(View.VISIBLE);
        }
        if (CommonUtil.isNetWorkConnected(this)) {
            setWebViewConfig(loadUrl);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log(TAG, "url=" + url);
//        if (url.contains("transactionDetail.html?")) {
//            String param = url.split("\\?")[1];
//            System.out.println("param---" + param);
//            mIntent.putExtra("param", param);
//            mIntent.setClass(mActivity, AssetsFundDetailActivity.class);
//            startActivity(mIntent);
//        } else
//        tradeRequestId = "";
//        tradeAccountNo = "";
//        canwithdraw = "0";
//        rightButton.setVisibility(View.GONE);
        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_LOGIN)) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
            EventBus.getDefault().post(new TimeOutEvent(true));
        } else if (url.contains(WebViewNetworkProtocol.GO_QUESTION)) {
            startRiskActivity(null);
        } else {
            webview.loadUrl(url);
        }
    }

    @OnClick(R.id.rightButton)
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            switch (view.getId()) {
                case R.id.rightButton:
                    if (url.contains("E207")) { //预约赎回直接输密码
                        inputPwd();
                    } else {
                        transationTips();
                    }
                    break;
                default:
                    super.onClick();
                    break;
            }
        }
    }

    private void transationTips() {
        IcbcDialog dialog = new IcbcDialog(mActivity);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        String contentText = "";
        //T020 	认购申请
        //T022 	申购申请
        //T039	定投申请
        //T024 	赎回申请
        //T036	基金转换申请
        if (url.contains("T020") || url.contains("T022")
                || url.contains("T039")) {//认购 申购 定投
            contentText = "您确定要撤销交易吗? 撤单后, 您的资金将于一个工作日内划出。";
        } else if (url.contains("T024") || url.contains("T036")) { //赎回 , 转换
            contentText = "您确定要撤销交易吗? 撤单后, 您的账户份额将实时恢复。";
        }
        dialog.setContentText(contentText);
        dialog.setEditTextType(false);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                inputPwd();
            }
        }).show();
    }

    /**
     * 用户确定撤单
     */
    private void isCancelTrade() {
        IcbcDialog dialog = new IcbcDialog(this);
        dialog.setColor("#ffffff");
        dialog.setTitleTop(5);
        dialog.setContentLeft(20);
        dialog.setContentRight(20);
        dialog.setContentTextGravity(Gravity.CENTER_HORIZONTAL);
        dialog.isContentTextHtml(true);
        dialog.setCancelable(false);
        dialog.setAnimationEnable(true);
        dialog.setTitle("提示");
        dialog.setContentText("您确定要撤销该交易吗？");
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
//                querySupportRealTimeCancelInfo();
            }
        });
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
            }

        }).show();
    }

    private void inputPwd() {
        IcbcDialog dialog = new IcbcDialog(this);
        dialog.setColor("#ffffff");
        dialog.setEditTextColor("#000000");
        dialog.setCancelable(false);
        dialog.setAnimationEnable(true);
        dialog.setTitle("输入密码");
        dialog.setEditTextType(true);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                String pwd = dialog.getEditTextContent();
                if (TextUtils.isEmpty(pwd)) {
                    showConfirmAlert(TransactionDetailActivity.this, "交易密码不能为空");
                    return;
                }
                String rsaKey = getRsaKey();
                String pwdEncode = "";
                if (!TextUtils.isEmpty(rsaKey)) {
                    pwdEncode = RSACryptographyUtil.encryptByPublicKey(pwd, rsaKey);
                }
                collapseSoftInputMethod(rightButton.getWindowToken());
                cancelTrade(pwdEncode);
            }
        }).show();

    }

    /**
     * 交易撤单
     */
    private void cancelTrade(String tradePassword) {

        if (StringUtils.isNullOrEmpty(tradePassword)) {
            return;
        }
        if (StringUtils.isNullOrEmpty(tradeAccountNo)) {
            showToast("缺少交易账号！");
            return;
        }
        if (StringUtils.isNullOrEmpty(tradeRequestId)) {
            showToast("缺少原交易申请单号！");
            return;
        }
        Map<String, String> params = new HashMap<>();

        params.put("tradeAccountNo", tradeAccountNo);//交易账号
        params.put("token", getToken());//Token
        params.put("fundCustomerNo", getFundCustomerNo());//客户号
        params.put("tradePassword", tradePassword);//交易密码
        params.put("applySerial", tradeRequestId);//原交易申请单号
        params.put("canceledBusinessType", canceledBusinessType);
        OkGo.<String>post(HostConstant.CANCEL_TRADE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析撤单接口返回的数据
     *
     * @param response
     */
    private void parseJson(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            hideLoading();
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            hideLoading();
            return;
        }
        finish();
    }

    /**
     * 64.	撤单时是否支持t+0快速赎回到账
     */
    private void querySupportRealTimeCancelInfo() {
//        交易账号	tradeAccountNo	M
//        Token	token
//        M
//        客户号	fundCustomerNo	M
//        交易密码	tradePassword	M
//        原交易申请单号	applySerial	M

        if (StringUtils.isNullOrEmpty(tradeAccountNo)) {
            hideLoading();
            showToast("缺少交易账号！");
            return;
        }
        if (StringUtils.isNullOrEmpty(tradeRequestId)) {
            hideLoading();
            showToast("缺少原交易申请单号！");
            return;
        }

        Map<String, String> params = new HashMap<>();

        params.put("sessionKey", getToken());//Token
        params.put("tradeAccountNo", tradeAccountNo);//交易账号
        params.put("applyserial", tradeRequestId);//原交易申请单号
        params.put("clientType", HostConstant.CLIENT_TYPE);//客户端类型

        OkGo.<String>post(HostConstant.QUERY_SUPPORT_REAL_TIME_CANCEL_INFO)
                .tag(this)
                .upJson(new Gson().toJson(HttpUtils.getCommonParams(this, params)))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoading();
                        parseRealTimeCancelInfoJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        hideLoading();
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideLoading();
                    }
                });
    }

    /**
     * 解析撤单时是否支持t+0快速赎回到账接口返回的数据
     *
     * @param response
     */
    private void parseRealTimeCancelInfoJson(String response) {
        QuerySupportRealTimeCancelInfo bean;
        try {
            bean = new Gson().fromJson(response, QuerySupportRealTimeCancelInfo.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (bean == null || StringUtils.isNullOrEmpty(bean.getErrorCode())) {
            showToast(MentorConst.SERVER_BUSY_TIP);
            return;
        }
        if (!"0000".equals(bean.getErrorCode())) {
            showConfirmAlert(this, bean.getErrorMessage());
            return;
        }
        if (bean.getData() == null || bean.getData().getQuickRedeem() == null) {
            showToast(MentorConst.SERVER_BUSY_TIP);
        }
//        showToast("撤单成功！");
        boolean isSuccess = bean.getData().getQuickRedeem();
        IcbcDialog dialog = new IcbcDialog(mActivity);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        String contentText = "";
        Log.e("lty", "是否是实时撤单:=" + isSuccess + "url为=" + url);
//        String contentType = isSuccess ? "账户份额将实时恢复。" : "资金将于一个工作日内划出。";
        //T020 	认购申请
        //T022 	申购申请
        //T039	定投申请
        //T024 	赎回申请
        //T036	基金转换申请
        if (url.contains("T020") || url.contains("T022")
                || url.contains("T039")) {//认购 申购 定投
            contentText = "您确定要撤销交易吗? 撤单后, 您的资金将于一个工作日内划出。";
        } else if (url.contains("T024") || url.contains("T036")) { //赎回 , 转换
            contentText = "您确定要撤销交易吗? 撤单后, 您的账户份额将实时恢复。";
        }
        dialog.setContentText(contentText);
//                dialog.setContentText("该产品超过了您的风险承受能力，是否继续交易？");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                inputPwd();
            }
        }).show();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
